/*
 * Copyright (c) 2009 Tamás Kovács <keccs *at* inbox.com>
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 * 
 */
package keccs.hitTheHay.ui;

import java.awt.Frame;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import keccs.hitTheHay.core.ApplicationModel;
import keccs.hitTheHay.core.ApplicationModel.ApplicationState;


class TitleUpdateListener implements PropertyChangeListener {
	private Frame mainFrame;

	public TitleUpdateListener(Frame mainFrame) {
		super();
		this.mainFrame = mainFrame;
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals("timeLeft") || evt.getPropertyName().equals("state")) { //$NON-NLS-1$ //$NON-NLS-2$
			String newTitle;
			if (ApplicationModel.getInstance().getState() == ApplicationState.COUNTDOWN) {
				long timeLeft = ApplicationModel.getInstance().getTimeLeft();
				String action = ApplicationModel.getInstance().getAction().toString();
				String timeLeftStr = convertTimeToString(timeLeft);
				newTitle = Messages.getString("TitleUpdateListener.CountdownWindowTitle", action, timeLeftStr); //$NON-NLS-1$
			} else {
				newTitle = Messages.getString("MainFrame.WindowTitle");
			}
			mainFrame.setTitle(newTitle);
		}
	}

	private String convertTimeToString(long time) {
		long minutes = time / 1000 / 60;
		long seconds = time / 1000 % 60;
		String secondsZeroPadded = seconds < 10 ? "0" + seconds : Long.toString(seconds); //$NON-NLS-1$
		return minutes + ":" + secondsZeroPadded; //$NON-NLS-1$
	}
}